package com.shardingjdbc.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.Arrays;
import java.util.Collection;

/**
 * @author by itheima
 * @Date 2022/1/19
 * @Description 定于数据库的分片策略
 */
public class RangeDBShardingAlgorithm implements RangeShardingAlgorithm<Long> {
    /**
     * 范围查询映射数据库
     * @param collection 所有逻辑数据库名称，比如ds1,ds2
     * @param rangeShardingValue 包含上限和下限名称的片键值
     * @return 返回可访问的数据库集合
     */
    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        //获取分片键名称
        String columnName = rangeShardingValue.getColumnName();
        System.out.println(columnName);
        //获取逻辑表名称
        String logicTableName = rangeShardingValue.getLogicTableName();
        System.out.println(logicTableName);
        //封装上限和下限值
        Range<Long> valueRange = rangeShardingValue.getValueRange();
        //判断是否有下限值
        if (valueRange.hasLowerBound()) {
            Long low = valueRange.lowerEndpoint();
            System.out.println(low);
        }
        //判断是否有上限值
        if (valueRange.hasUpperBound()) {
            Long upper = valueRange.upperEndpoint();
            System.out.println(upper);
        }
        return Arrays.asList("ds1","ds2");
    }
}
